package com.sauro.study.config;

import com.alibaba.fastjson.JSON;
import com.sauro.util.DateUtil;
import com.sauro.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求拦截器
 * 可在此处加上相关拦截
 */
public class ProjectRequestInterceptor extends HandlerInterceptorAdapter {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Long start = System.currentTimeMillis();
        String startTime = DateUtil.getDateTime(DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS_SSS);
        String tranceId = UUID.randomUUID().toString() + System.currentTimeMillis();
        MDC.put("tranceId", tranceId);
        MDC.put("startTime", startTime);
        startTimeThreadLocal.set(start);


        logger.info("module=拦截器;event=进入controller;msg=" + request.getServletPath() + ";startTime=" + startTime + ";method="
                + request.getMethod() + ";host=" + WebUtil.getHost(request) + "url=" + request.getRequestURL()
                + "param:" + JSON.toJSONString(request.getParameterMap()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String returneValue = String.valueOf(request.getAttribute("response"));
        if (StringUtils.isBlank(returneValue)) {
            returneValue = "返回值为null";
        }

        long spend = System.currentTimeMillis() - startTimeThreadLocal.get();
        String endTime = DateUtil.getDateTime(DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS_SSS);
        logger.info("module=拦截器;event=退出controller;msg=" + request.getServletPath() + ";result=" + returneValue + ";spend="
                + spend + ";endTime=" + endTime + ";method=" + request.getMethod());
        super.afterCompletion(request, response, handler, ex);
    }


}
